// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.warehouse.viewers.database;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.dengues.commons.IDenguesSharedImage;
import org.dengues.commons.utils.DenguesTextUtil;
import org.dengues.commons.utils.ImageUtil;
import org.dengues.core.components.ENodeParameterName;
import org.dengues.core.connectivity.IConnectivityProperty;
import org.dengues.core.property.NodeParameterUtils;
import org.dengues.core.resource.WarehouseResourceFactory;
import org.dengues.core.warehouse.ENodeCategoryName;
import org.dengues.core.warehouse.ENodeStatus;
import org.dengues.designer.ui.DesignerUIPlugin;
import org.dengues.model.database.DatabaseDiagram;
import org.dengues.ui.prefs.connectivity.EConnectivityProperties;
import org.dengues.warehouse.i18n.Messages;
import org.dengues.warehouse.viewers.action.OpenPrefsSettingsAction;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf 2007-11-27 qiang.zhang $
 * 
 */
public class NewDatabaseWizardPage extends WizardPage {

    private String databaseName;

    private String databaseComment;

    private IStatus nameStatus;

    private DatabaseDiagram database;

    private boolean isQuery;

    private boolean isActived;

    /**
     * Qiang.Zhang.Adolf@gmail.com NewDatabaseWizardPage constructor comment.
     */
    private NewDatabaseWizardPage() {
        super(Messages.getString("NewDatabaseWizardPage.0")); //$NON-NLS-1$
        nameStatus = createOkStatus();
        setTitle(Messages.getString("NewDatabaseWizardPage.Title")); //$NON-NLS-1$
        setDescription(Messages.getString("NewDatabaseWizardPage.Description")); //$NON-NLS-1$
        properties = new Properties();
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com NewDatabaseWizardPage constructor comment.
     * 
     * @param database
     */
    private NewDatabaseWizardPage(DatabaseDiagram database) {
        this();
        this.database = database;
        setTitle(Messages.getString("NewDatabaseWizard.editproperties")); //$NON-NLS-1$
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com NewDatabaseWizardPage constructor comment.
     * 
     * @param database
     * @param isQuery
     */
    public NewDatabaseWizardPage(DatabaseDiagram database, boolean isQuery, boolean isActived) {
        this(database);
        this.isQuery = isQuery;
        this.isActived = isActived;
    }

    private Text nameText;

    private Text commentText;

    private Table connPropertiesTable;

    private final Properties properties;

    private String propId = ""; //$NON-NLS-1$

    private Combo combo;

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
     */
    public void createControl(Composite parent) {
        GridLayout layout = new GridLayout();
        GridData gridData = new GridData(GridData.FILL_BOTH);
        Composite container = new Composite(parent, SWT.NONE);
        layout = new GridLayout();
        layout.marginBottom = 0;
        layout.marginHeight = 0;
        layout.marginLeft = 0;
        layout.marginRight = 0;
        layout.marginTop = 0;
        layout.marginWidth = 0;
        container.setLayout(layout);
        gridData = new GridData(GridData.FILL_BOTH);
        container.setLayoutData(gridData);
        Composite generic = new Composite(container, SWT.NONE);
        layout = new GridLayout(2, false);
        layout.marginBottom = 0;
        layout.marginHeight = 0;
        layout.marginLeft = 0;
        layout.marginRight = 0;
        layout.marginTop = 0;
        layout.marginWidth = 0;
        generic.setLayout(layout);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        generic.setLayoutData(gridData);
        Label nameLab = new Label(generic, SWT.NONE);
        nameLab.setText(Messages.getString("NewDatabaseWizardPage.Label.Name")); //$NON-NLS-1$

        nameText = new Text(generic, SWT.BORDER);
        nameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        if (database != null) {
            databaseName = DenguesTextUtil.getNotNullString(database.getName());
            nameText.setText(databaseName);
        }
        Label commentLab = new Label(generic, SWT.NONE);
        commentLab.setText(Messages.getString("NewDatabaseWizardPage.Label.Comment")); //$NON-NLS-1$

        commentText = new Text(generic, SWT.BORDER | SWT.MULTI);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        gridData.heightHint = 60;
        commentText.setLayoutData(gridData);

        if (database != null) {
            databaseComment = DenguesTextUtil.getNotNullString((String) database.getProperties().get(
                    ENodeParameterName.DB_COMMENT.getName()));
            commentText.setText(databaseComment);
        }

        addConnectivityInfo(container);

        setControl(container);
        setPageComplete(false);
        addListeners();
        checkFieldsValue();
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "addConnectivityInfo".
     * 
     * @param container
     */
    private void addConnectivityInfo(final Composite container) {
        final Group group = new Group(container, SWT.NONE);
        group.setText(Messages.getString("NewDatabaseWizardPage.info")); //$NON-NLS-1$
        GridLayout gridLayout = new GridLayout();
        gridLayout.marginBottom = 0;
        gridLayout.marginHeight = 0;
        gridLayout.marginLeft = 0;
        gridLayout.marginRight = 0;
        gridLayout.marginTop = 0;
        gridLayout.marginWidth = 0;

        group.setLayout(gridLayout);
        GridData gridData = new GridData(GridData.FILL_BOTH);
        group.setLayoutData(gridData);
        Composite comboLabel = new Composite(group, SWT.NONE);
        gridLayout = new GridLayout(3, false);
        gridLayout.marginBottom = 0;
        gridLayout.marginHeight = 0;
        gridLayout.marginLeft = 0;
        gridLayout.marginRight = 0;
        gridLayout.marginTop = 0;
        gridLayout.marginWidth = 0;
        comboLabel.setLayout(gridLayout);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        comboLabel.setLayoutData(gridData);

        Label label = new Label(comboLabel, SWT.NONE);
        label.setText(Messages.getString("NewDatabaseWizardPage.name")); //$NON-NLS-1$
        combo = new Combo(comboLabel, SWT.READ_ONLY);
        final Map<String, IConnectivityProperty> connectivityProperties = NodeParameterUtils.getConnectivityProperties();
        combo.setItems(connectivityProperties.keySet().toArray(new String[0]));
        if (database != null && database.getConnId() != null) {
            combo.setText(database.getConnId());
        }
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        combo.setLayoutData(gridData);
        combo.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                updateProperties(combo, connectivityProperties);
            }
        });
        Button button = new Button(comboLabel, SWT.PUSH);
        button.setImage(ImageUtil.getImage(IDenguesSharedImage.PREFS_CONNSET));
        button.setToolTipText(Messages.getString("NewDatabaseWizardPage.setting")); //$NON-NLS-1$
        button.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                new OpenPrefsSettingsAction().run();
            }
        });
        connPropertiesTable = new Table(group, SWT.BORDER | SWT.FULL_SELECTION);
        connPropertiesTable.setHeaderVisible(true);
        connPropertiesTable.setLinesVisible(true);
        gridData = new GridData(GridData.FILL_BOTH);
        connPropertiesTable.setLayoutData(gridData);
        TableColumn column = new TableColumn(connPropertiesTable, SWT.NONE);
        column.setText(Messages.getString("NewDatabaseWizardPage.propName")); //$NON-NLS-1$
        column.pack();
        column = new TableColumn(connPropertiesTable, SWT.NONE);
        column.setText(Messages.getString("NewDatabaseWizardPage.propValue")); //$NON-NLS-1$
        column.pack();
        updateProperties(combo, connectivityProperties);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "checkFieldsValue".
     */
    private void checkFieldsValue() {
        if (!isActived) {
            if (nameText.getText().length() == 0) {
                nameStatus = new Status(IStatus.ERROR, DesignerUIPlugin.PLUGIN_ID, IStatus.ERROR, Messages
                        .getString("NewDatabaseWizardPage.Empty"), null); //$NON-NLS-1$
            } else {
                if (isDatabaseNameAlreadyUsed(nameText.getText())) {
                    nameStatus = new Status(IStatus.ERROR, DesignerUIPlugin.PLUGIN_ID, IStatus.ERROR, Messages
                            .getString("NewDatabaseWizardPage.Exist"), null); //$NON-NLS-1$
                } else {
                    nameStatus = createOkStatus();
                }
            }
            setMessage(nameStatus);
            boolean b = nameStatus.getSeverity() != IStatus.ERROR;
            setPageComplete(b);
            if (b) {
                databaseName = nameText.getText();
            }
        } else {
            nameText.setEnabled(false);
            connPropertiesTable.setEnabled(false);
            commentText.setEnabled(false);
            combo.setEnabled(false);
            setPageComplete(false);
            setErrorMessage(Messages.getString("NewProcessWizardPage.isActivedMsg")); //$NON-NLS-1$
        }
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "isDatabaseNameAlreadyUsed".
     * 
     * @param text
     * @return
     */
    private boolean isDatabaseNameAlreadyUsed(String text) {
        List<String> names = WarehouseResourceFactory.getAllObjectNamesFromEMF(ENodeCategoryName.DATABASE);
        if (database != null && database.getName().equals(text)) {
            return false;
        }
        return names.contains(text);
    }

    /**
     * zx Comment method "addListeners".
     */
    private void addListeners() {
        nameText.addModifyListener(new ModifyListener() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
             */
            public void modifyText(ModifyEvent e) {
                checkFieldsValue();
            }

        });
        commentText.addModifyListener(new ModifyListener() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
             */
            public void modifyText(ModifyEvent e) {
                databaseComment = commentText.getText();
            }
        });
    }

    /**
     * zx Comment method "getComment".
     * 
     * @return
     */
    public String getDatabaseComment() {
        return DenguesTextUtil.getNotNullString(databaseComment);
    }

    public String getDatabaseName() {
        return DenguesTextUtil.getNotNullString(databaseName);
    }

    public String getDatabaseStatus() {
        return ENodeStatus.NORMAL.getId();
    }

    private void setMessage(IStatus status) {
        if (IStatus.ERROR == status.getSeverity()) {
            setErrorMessage(status.getMessage());
            setMessage(""); //$NON-NLS-1$
        } else {
            setMessage(status.getMessage());
            setErrorMessage(null);
        }
    }

    private static IStatus createOkStatus() {
        return new Status(IStatus.OK, DesignerUIPlugin.PLUGIN_ID, IStatus.OK, "", null); //$NON-NLS-1$
    }

    public Properties getProperties() {
        return this.properties;
    }

    public String getPropId() {
        return this.propId;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "updateProperties".
     * 
     * @param combo
     * @param connectivityProperties
     */
    private void updateProperties(final Combo combo, final Map<String, IConnectivityProperty> connectivityProperties) {
        IConnectivityProperty connectivityProperty = connectivityProperties.get(combo.getText());
        if (connectivityProperty == null) {
            return;
        }
        Properties baseProperties = connectivityProperty.getBaseProperties();
        Set<Object> keySet = baseProperties.keySet();
        connPropertiesTable.clearAll();
        properties.clear();
        List<String> connIds = new ArrayList<String>();
        String[] array = keySet.toArray(new String[0]);
        for (String string : array) {
            if (EConnectivityProperties.getDisplayNameFromId(string) != null) {
                connIds.add(string);
            }
        }
        int itemCount = connPropertiesTable.getItemCount();
        if (connIds.size() > itemCount) {
            for (int i = 0; i < connIds.size() - itemCount; i++) {
                new TableItem(connPropertiesTable, SWT.NONE);
            }
        } else {
            for (int i = connIds.size(); i < itemCount; i++) {
                connPropertiesTable.getItem(i).dispose();
            }
        }
        for (int i = 0; i < connIds.size(); i++) {
            String name = connIds.get(i);
            String property = baseProperties.getProperty(name);
            properties.setProperty(name, property);
            connPropertiesTable.getItem(i).setText(new String[] { EConnectivityProperties.getDisplayNameFromId(name), property });
        }
        for (int i = 0; i < connPropertiesTable.getColumnCount(); i++) {
            connPropertiesTable.getColumn(i).pack();
        }
        propId = combo.getText();
    }
}
